//
// perc2 - calculation of the fractal dimension of correlated
// bond percolation cluster hulls
//
// Copyright (C) 2009, 2010 Indrek Mandre <indrek(at)mare.ee>
// http://www.mare.ee/indrek/perc2/, http://code.google.com/p/perc2/
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// 

//#define PRINTOUT

#include "common.cpp"

static void usage (const char *argv0)
{
  fprintf (stderr, "%s: %s [-e exponent] [-n] [-p factor] [-r seed] [-R rnd.bin] [-o perc.csv] [-s samplecount] [-i start end] [-g generator] [-b] [-l growthpow startlayer endlayer]\n", argv0, argv0);
  fprintf (stderr, "    -e exponent - set the correlation exponent\n");
  fprintf (stderr, "    -n - non-progressive calculation\n");
  fprintf (stderr, "    -p factor - specify the progression factor\n");
  fprintf (stderr, "    -r seed - set the random seed\n");
  fprintf (stderr, "    -R rnd.bin - random binary bitstream data\n");
  fprintf (stderr, "    -o perc.csv - output data to file\n");
  fprintf (stderr, "    -s samplecount - how many samples to do at first level\n");
  fprintf (stderr, "    -i start end - calculate with A from start to end\n");
  fprintf (stderr, "    -g generator - use the given random generator, put 'list' to see available\n");
  fprintf (stderr, "    -b - add baseline\n");
  fprintf (stderr, "    -m - use only 0 potential for sealevel and no perimeter edge test\n");
  fprintf (stderr, "    -l growthpow startlayer endlayer - specify the layer growth base and layer range\n");
  exit(-1);
}

int main (int argc, char *argv[])
{
  big_t SAMPLES = 16384;
  bool progressive = true;
  const char *outfn = "perc.csv";
  int start = 32;
  int end = 2048;
  int rnd_seed = 0;
  EXPONENT = 0.75;
  bool add_baseline = false;
  double pf = 2.0;
  const char *rndpath = 0;
  bool middle = false;

  const gsl_rng_type * rng_type = gsl_rng_default;

  for ( int i = 1; i < argc; i++ )
    {
      if ( argv[i][0] != '-' || argv[i][1] == 0 || argv[i][2] != 0 )
          usage (argv[0]);

      switch (argv[i][1])
        {
          case 'i': {
            if ( i + 2 >= argc )
                usage(argv[0]);
            if ( sscanf (argv[++i], "%d", &start) != 1 ||
                sscanf (argv[++i], "%d", &end) != 1 ||
                start < 1 || end < start )
                usage (argv[0]);
            break;
          }
          case 'n': {
            progressive = false;
            break;
          }
          case 'b': {
            add_baseline = true;
            break;
          }
          case 'm': {
            middle = true;
            break;
          }
          case 'o': {
            i++;
            if ( i == argc )
                usage (argv[0]);
            outfn = argv[i];
            break;
          }
          case 'r': {
            i++;
            if ( i == argc || sscanf (argv[i], "%d", &rnd_seed) != 1 )
                usage (argv[0]);
            break;
          }
          case 'R': {
            i++;
            if ( i == argc )
                usage (argv[0]);
            rndpath = argv[i];
            break;
          }
          case 'p': {
            i++;
            if ( i == argc || sscanf (argv[i], "%lf", &pf) != 1 )
                usage (argv[0]);
            break;
          }
          case 'e': {
            i++;
            if ( i == argc || sscanf (argv[i], "%lf", &EXPONENT) != 1 )
                usage (argv[0]);
            break;
          }
          case 'l': {
            if ( i++ == argc || sscanf (argv[i], "%lf", &BASEPOW) != 1 ||
                i++ == argc || sscanf (argv[i], "%d", &LAYERSTART) != 1 ||
                i++ == argc || sscanf (argv[i], "%d", &LAYEREND) != 1 )
                usage (argv[0]);
            break;
          }
          case 's': {
            i++;
            if ( i == argc || sscanf (argv[i], "%llu", &SAMPLES) != 1 )
                usage (argv[0]);
            break;
          }
          case 'g': {
            i++;
            if ( i == argc )
                usage (argv[0]);
            rng_type = 0;
            for ( const gsl_rng_type **t = gsl_rng_types_setup(); *t != 0; t++ )
              {
                if ( strcmp ((*t)->name, argv[i]) == 0 )
                  {
                    rng_type = *t;
                    break;
                  }
              }
            if ( !rng_type )
              {
                printf ("Random generators available:\n");
                for ( const gsl_rng_type **t = gsl_rng_types_setup(); *t != 0; t++ )
                    printf ("  %s\n", (*t)->name);
                exit(0);
              }
            break;
          }
          default: {
            usage (argv[0]);
            break;
          }
        }
    }

  if ( 2 * end > FIELD_SIZE )
    {
      fprintf (stderr, "Error: interval too large for the compile time field size!\n");
      abort();
    }

  rndf.seed (rng_type, rnd_seed, rndpath);

  printf ("Using random generator: %s\n", rng_type->name);
  printf ("Random seed at %d\n", rnd_seed);
#ifdef UNCORRELATED
  printf ("Uncorrelated, ignoring the correlation exponent\n");
#else
  printf ("Correlation exponent is %f\n", EXPONENT);
  printf ("Cumulation %d\n", CUMULATION);
  printf ("Layer size growth power %g\n", (double)BASEPOW);
  printf ("Adding baseline: %s\n", add_baseline ? "YES" : "NO");
#endif
  printf ("Field size %d\n", FIELD_SIZE);


  //calc_cell_dist (outfn);
  //calc_dist (outfn);
  //exit(0);

  Field *f = new Field(add_baseline);

  //exit(0);
  //f->printsurf("surf.dat", 4096, 2048, false);
  //f->testdim();

  printf ("Running, %s from %llu samples\n", progressive ? "progressive" : "non-progressive", SAMPLES);

#ifndef PRINTOUT
  FILE *fpcsv = fopen (outfn, "w");
  if ( !fpcsv )
      exit(-1);

  printf ("Writing data into '%s'..\n", outfn);

  fprintf (fpcsv, "A(BONDS,FULLS,LINES),M,SAMPLES,SUM(V1),SUM(V2),...,SUM(VM),"
      "SUM(V1*V1),SUM(V1*V2),...,SUM(V1*VM),SUM(V2*V2),SUM(V2*V3),...,SUM(VM*VM)\n");
  fflush (fpcsv);
#endif

  double SC = SAMPLES;

  std::vector<std::pair<int,int> > lookinto;
  std::vector<std::pair<int,int> > buildup;
  for ( double scale = start; scale <= end; scale *= pf, SC /= (progressive ? pf : 1.0) )
    {
      SAMPLES = SC;
      int A = scale;

#ifndef PRINTOUT
      printf ("Calculating A=%d, %llu samples..\n", A, SAMPLES);
#endif

      int first = 0;
      int last = first + A + 2;
      int mid = (first + last) / 2;
      int offset = FIELD_SIZE / 2 - mid;

      fbitmap valmap(last - first);

      aggregator<12> aggr;
      size_t samples = 0;
      while ( SAMPLES > samples )
        {
          f->reset();
          int x = mid;
          int y = mid;

          coord_t start;
          start.pos.x = offset + x;
          start.pos.y = offset + y;
          start.low = rndf.rnd() >= 0;


          Walker walker(f, start);

          if ( !middle )
            {
#ifndef UNCORRELATED
              f->set_sealevel (f->value (offset + x, offset + y));
#endif

              if ( !walker.walk_perim2 (last - first) )
                  continue;
            }
          else
            {
              if ( !f->valueb (offset + x, offset + y) )
                  continue;
            }

          valmap.clear();

          lookinto.clear();
          buildup.clear();

          lookinto.push_back (std::pair<int,int>(x, y));

          bool left, right, up, down;
          left = right = up = down = false;

          // setup
          int limit = last - first;
          static Bitmap bmap(32);
          bmap.reset (limit + 1);
          int hlimit = limit / 2;
          coord_t save;

          // first wind forward
          coord_t cur = start;
          while ( 1 )
            {
              if ( abs (start.pos.x - cur.pos.x) == hlimit || abs (start.pos.y - cur.pos.y) == hlimit )
                  break;

              save = cur;

              if ( f->valueb (cur.pos.x, cur.pos.y) )
                {
                  bmap.set (cur.pos.x - start.pos.x, cur.pos.y - start.pos.y);
                  cur.hamster();
                }
              else
                {
                  cur.punch();
                  cur.hamster();
                }
            }

          coord_t end = save;

          // then wind backwards
          cur = start;
          while ( 1 )
            {
              if ( abs (start.pos.x - cur.pos.x) == hlimit || abs (start.pos.y - cur.pos.y) == hlimit )
                  break;

              save = cur;

              if ( f->valueb (cur.pos.x, cur.pos.y) )
                {
                  bmap.set (cur.pos.x - start.pos.x, cur.pos.y - start.pos.y);
                  cur.rhamster();
                }
              else
                {
                  cur.punch();
                  cur.rhamster();
                }
            }

          coord_t begin = save;
          if ( !bmap.get (begin.pos.x - start.pos.x, begin.pos.y - start.pos.y) )
              begin.punch();

          //printf ("begin=%d %d %d, end=%d %d %d\n",
          //    begin.pos.x - start.pos.x, begin.pos.y - start.pos.y, begin.low,
          //    end.pos.x - start.pos.x, end.pos.y - start.pos.y, end.low);

          // now trace the perimeter
          cur = begin;

          while ( 1 )
            {
              if ( cur.pos.x == end.pos.x && cur.pos.y == end.pos.y )
                  break;

              int rx = cur.pos.x - start.pos.x;
              int ry = cur.pos.y - start.pos.y;
              bool bounce = bmap.get (rx, ry);

              //printf ("Looping: %d %d %d\n", rx, ry, bounce);
              if ( !bounce )
                {
                  if ( (cur.pos.x ^ cur.pos.y) & 1 )
                    {
                      if ( cur.low )
                        {
                          if ((bmap.get (rx + 1, ry) || bmap.get (rx + 1, ry + 1) || bmap.get (rx, ry + 1)) &&
                              (bmap.get (rx - 1, ry - 1) || bmap.get (rx, ry - 1) || bmap.get (rx - 1, ry)))
                              bounce = true;
                        }
                      else
                        {
                          if ((bmap.get (rx + 1, ry + 1) || bmap.get (rx, ry + 1) || bmap.get (rx + 1, ry)) &&
                              (bmap.get (rx - 1, ry) || bmap.get (rx - 1, ry - 1) || bmap.get (rx, ry - 1)))
                              bounce = true;
                        }
                    }
                  else
                    {
                      if ( cur.low )
                        {
                          if ((bmap.get (rx + 1, ry - 1) || bmap.get (rx, ry - 1) || bmap.get (rx + 1, ry)) &&
                              (bmap.get (rx - 1, ry) || bmap.get (rx - 1, ry + 1) || bmap.get (rx, ry + 1)))
                              bounce = true;
                        }
                      else
                        {
                          if ((bmap.get (rx + 1, ry) || bmap.get (rx + 1, ry - 1) || bmap.get (rx, ry - 1)) &&
                              (bmap.get (rx, ry + 1) || bmap.get (rx - 1, ry + 1) || bmap.get (rx - 1, ry)))
                              bounce = true;
                        }
                    }
                }

              if ( bounce )
                {
                  valmap.set (cur.pos.x - offset, cur.pos.y - offset);
                  cur.hamster();
                }
              else
                {
                  cur.punch();
                  cur.hamster();
                }
            }
          

#ifdef PRINTOUT
          Walker::grid_t grid;
#endif
          size_t ocean, ones, twos, lots;
          ocean = ones = twos = lots = 0;
          for ( int y = first + 1; y <= last - 2; y++ )
            {
              for ( int x = first + 1; x <= last - 2; x++ )
                {
#ifdef PRINTOUT
                  if ( valmap.get (x, y) )
                      grid.push_back (pos_t(x, y));
#endif
                  if ( !valmap.get(x, y) )
                    {
                      int cnt = 0;
                      if ( Field::upw (x, y) )
                        {
                          cnt += valmap.get (x, y + 1) ? 1 : 0;
                          cnt += valmap.get (x + 1, y) ? 1 : 0;
                          cnt += valmap.get (x + 1, y + 1) ? 1 : 0;
                          cnt += valmap.get (x, y - 1) ? 1 : 0;
                          cnt += valmap.get (x - 1, y) ? 1 : 0;
                          cnt += valmap.get (x - 1, y - 1) ? 1 : 0;
                        }
                      else
                        {
                          cnt += valmap.get (x, y + 1) ? 1 : 0;
                          cnt += valmap.get (x + 1, y) ? 1 : 0;
                          cnt += valmap.get (x + 1, y - 1) ? 1 : 0;
                          cnt += valmap.get (x, y - 1) ? 1 : 0;
                          cnt += valmap.get (x - 1, y) ? 1 : 0;
                          cnt += valmap.get (x - 1, y + 1) ? 1 : 0;
                        }
                      if ( cnt )
                        {
                          ocean++;
                          if ( cnt == 1 )
                              ones++;
                          else if ( cnt == 2 )
                              twos++;
                          else if ( cnt >= 3 )
                              lots++;
                        }
                    }
                }
            }

          aggr.add (
              ocean, ones, lots, twos,
              walker.get_perim(),
              walker.get_bonds(),
              walker.get_ends(),
              walker.get_lines(),
              walker.get_holes(),
              walker.get_fjords(),
              walker.get_corners(),
              0);

          //printf ("Found: %zu %d %d %d %d\n", cluster_size, left, right, up, down);
#ifdef PRINTOUT
          Walker::print_grid ("printout_grid.csv", grid);
          break;
#endif
          samples++;
        }
#ifndef PRINTOUT
      assert ( samples == SAMPLES);
      fprintf (fpcsv, "%d,%s\n", A, aggr.sprint());
      fflush (fpcsv);
#else
      break;
#endif
    }
  delete f;

#ifndef PRINTOUT
  fclose (fpcsv);
#endif
  return 0;
}

